<?php 
namespace town\tool;


/**
 * 分页样式渲染
 * pure.css 样式兼容
 */
class Page
{

	public $html = [
		'item' => '<li class="pure-menu-item %s"><a href="%s" class="pure-menu-link">%s</a></li>',
		'prev' => '<li class="pure-menu-item %s"><a href="%s" class="pure-menu-link">%s</a></li>',
		'next' => '<li class="pure-menu-item %s"><a href="%s" class="pure-menu-link">%s</a></li>',
		'html' => ''
	];

	// 启始行
	public $startRow = 1;

	// 取多少条记录
	public $takeNum = 10;


	/**
	 * $count 总数
	 * $size  大小
	 */
	public function __construct($count, $size = 10, $page = 0, $args = [])
	{
		$this->size  = $size;
		$this->count = $count;
		$this->args  = $args;
		if ($page < 1) {
			$page = $_GET['town_p'];
		}
		if ($page < 1) {
			$page = 1;
		}
		$this->page     = $page;
		$this->takeNum  = $size;
		$this->startRow = ($page-1) * $size;
	}


	/**
	 * 解析用户样式表
	 */	
	private function _parse()
	{
		if ($this->count < $this->size) {
			$this->html['html'] = '';
			return ;
		}
		// 拼接 url
		$total= ceil($this->count/$this->size);
		$base = $this->_base();
		$args = $this->_args();

		// item 拼接
		$link = '';
		$pagenation = '';
		$itemcss = $this->html['item'];
		for ($i=1; $i <= $total; $i++) { 
			$disable = '';
			if ($i == $this->page) {
				$disable = ' pure-button-disabled ';
			}
			$link = "{$base}/?town_p={$i}&{$args}";
			$pagenation .= sprintf($itemcss, $disable, $link, $i);;
		}

		// prev
		$css  = '';
		$prev = $this->html['prev'];
		$num  = ($this->page - 1);
		if ($num <= 1) {
			$css = ' pure-button-disabled ';
			$num = 1;
		}
		$link = "{$base}/?town_p={$num}&{$args}";
		$prev = sprintf($prev, $css, $link, '上一页');

		// next
		$css  = '';
		$next = $this->html['next'];
		$num  = ($this->page + 1);
		if ($num >= $total) {
			$css = ' pure-button-disabled ';
			$num = $total;
		}
		$link = "{$base}/?town_p={$num}&{$args}";
		$next = sprintf($next, $css, $link, '下一页');

		$html = '<div class="pure-menu pure-menu-horizontal pure-menu-scrollable">'
			.'<ul class="pure-menu-list">'.$prev.$pagenation.$next.'</ul></div>';
		$this->html['html'] = $html;
	}


	private function _args()
	{
		if (empty($this->args) || !is_array($this->args)) {
			return '';
		}
		$query = '';
		foreach ($this->args as $key => $value) {
			$query .= "&{$key}={$value}";
		}
		return ltrim($query, '&');
	}


	/**
	 * 判断是否是HTTPS链接
	 * 拼接绝对的基本路径
	 */	
	private function _base()
	{
    	$isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || ($_SERVER['SERVER_PORT'] == 443);
    	$schema   = $isSecure ? 'http' : 'https';
		return rtrim("{$schema}://{$_SERVER['HTTP_HOST']}{$_SERVER['REDIRECT_URL']}", '/');
	}


	/**
	 * 获取html
	 */
	public function html()
	{
		$this->_parse();
		return $this->html['html'];
	}


	/**
	 * 获取json
	 */
	public function json()
	{
		# code...
	}

}